from rest_framework import serializers
from rest_framework.decorators import action

from dvadmin.lowcode.models import LowDataTyped
from dvadmin.system.views.menu_button import MenuButtonSerializer
from dvadmin.utils.json_response import SuccessResponse,SuccessResponseTree
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
import json
from dvadmin.utils.tree import get_trees
class LowDataTypedSerializer(CustomModelSerializer):
    """
    数据类型序列化器
    """

    class Meta:
        model = LowDataTyped
        fields = "__all__"
        read_only_fields = ["id"]


class NewWebRouterSerializer(CustomModelSerializer):
    """
    前端菜单路由的简单序列化器
    """
    value = serializers.IntegerField(source="id")
    label = serializers.CharField(source="name")

    class Meta:
        model = LowDataTyped
        fields = '__all__'
        fields = ('label', 'value','pid','id')


class LowDataTypedViewSet(CustomModelViewSet):
    """
    数据类型管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = LowDataTyped.objects.all()
    serializer_class = LowDataTypedSerializer
    extra_filter_backends = []

    @action(methods=['GET'], detail=False, permission_classes=[])
    def tree(self, request):
        """用于前端菜单树结构树"""
        serializer = NewWebRouterSerializer(self.queryset.all(), many=True, request=request)
        data = serializer.data
        return SuccessResponse(data=data, total=len(data), msg="获取成功")

    @action(methods=['GET'], detail=False, permission_classes=[])
    def treev2(self, request):
        """用于前端菜单树结构树"""
        serializer = NewWebRouterSerializer(self.queryset.all(), many=True, request=request)
        data = serializer.data
        return SuccessResponse(data=get_trees(data,'id','pid','children'), total=len(data), msg="获取成功")

